﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Coomtools.commclass
{
    //××××××××××××××××××××××××××××使用说明××××××××××××××××××××××××××××××
    //**********使指定控件可以 拖到改变位置和大小的类 适用与模板设计××××××××××××××
    //××××××   调用方法  new MoveControl(ctrl as Control) ctrl 是要移动的控件name ××××××××××
    //×××目前添加了对键盘可以引动指定控件 其  ctrl必须是拥有keydown事件的控件不然该控件用键盘移动不正常例如：label控件
    // ×××使用该类的主窗体容器需要添加一下代码 目的是，主窗体屏蔽自动处理键盘的方向键不然会造成不响应keydown事件×××××××
    //protected override bool ProcessDialogKey(Keys keyData)
    //{
    //    if (keyData == Keys.Up || keyData == Keys.Down || keyData == Keys.Left || keyData == Keys.Right)
    //        return false;
    //    return base.ProcessDialogKey(keyData);
    //}
    //××××××××××××××××××××××××××××使用说明结束**********************************************************



    //   
    /// <summary>
    /// 使指定控件可以 拖到改变位置和大小的类
    /// </summary>
    public class MoveControl
    {


        #region Constructors
        public MoveControl(Control ctrl)
        {
            currentControl = ctrl;
            AddEvents();
        }
        #endregion
        #region 添加的字段
        public int NewTop { get; set; }
        public int NewLeft { get; set; }
        public int NewWidth { get; set; }
        public int NewHeight { get; set; }
        private const int Band = 8;


        private Control currentControl; //传入的控件
        private Point pPoint; //上个鼠标坐标
        private Point cPoint; //当前鼠标坐标
        FrameControl fc;//边框控件
        #endregion
        #region Properties
        #endregion
        #region 实现方法
        /// <summary>
        /// 挂载事件
        /// </summary>
        private void AddEvents()
        {
            currentControl.MouseClick += new MouseEventHandler(MouseClick);
            currentControl.MouseDown += new MouseEventHandler(MouseDown);
            currentControl.MouseMove += new MouseEventHandler(MouseMove);
            currentControl.MouseUp += new MouseEventHandler(MouseUp);
            currentControl.KeyDown += new KeyEventHandler(myKeydown);
        }
        /// <summary>
        /// 绘制拖拉时的黑色边框
        /// </summary>
        public static void DrawDragBound(Control ctrl)
        {
            ctrl.Refresh();
            Graphics g = ctrl.CreateGraphics();
            int width = ctrl.Width;
            int height = ctrl.Height;
            Point[] ps = new Point[5]{new Point(0,0),new Point(width -1,0),
   new Point(width -1,height -1),new Point(0,height-1),new Point(0,0)};
            g.DrawLines(new Pen(Color.Black), ps);
        }
        #endregion
        #region Events
        /// <summary>
        /// 鼠标单击事件：用来显示边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void MouseClick(object sender, MouseEventArgs e)
        {
            this.currentControl.Parent.Refresh();//刷新父容器，清除掉其他控件的边框
            this.currentControl.BringToFront();
            fc = new FrameControl(this.currentControl);
            this.currentControl.Parent.Controls.Add(fc);
            fc.Visible = true;
            fc.Draw();
        }
        /// <summary>
        /// 鼠标按下事件：记录当前鼠标相对窗体的坐标
        /// </summary>
        void MouseDown(object sender, MouseEventArgs e)
        {
            pPoint = Cursor.Position;
        }
        /// <summary>
        /// 鼠标移动事件：让控件跟着鼠标移动
        /// </summary>
        void MouseMove(object sender, MouseEventArgs e)
        {
            Cursor.Current = Cursors.SizeAll; //当鼠标处于控件内部时，显示光标样式为SizeAll
                                              //当鼠标左键按下时才触发
            if (e.Button == MouseButtons.Left)
            {
                MoveControl.DrawDragBound(this.currentControl);
                if (fc != null) fc.Visible = false; //先隐藏
                cPoint = Cursor.Position;//获得当前鼠标位置
                int x = cPoint.X - pPoint.X;
                int y = cPoint.Y - pPoint.Y;


                //检查 控件 是否移动到了父控件以外************************************
                int new_locationX = currentControl.Location.X + x;
                int new_locationY = currentControl.Location.Y + y;

                // 控件超出容器最小边框，把top 或 lef 设置为0+调节控件边框 band 设置为8
                if (new_locationX < 0)
                {
                    new_locationX = 0 + Band;
                }
                if (new_locationY < 0)
                {
                    new_locationY = 0 + Band;
                }
                //控件超出容器的最大边框 处理不能移出 容器
                //计算 容器的 大小 和 容器可工作区域的差， 不然 本控件还会移出容器一点
                int xx = currentControl.Parent.Width - currentControl.Parent.ClientRectangle.Width;
                int yy = currentControl.Parent.Height - currentControl.Parent.ClientRectangle.Height;

                if (new_locationX + currentControl.Width + xx > currentControl.Parent.Width)
                {
                    new_locationX = currentControl.Parent.Width - currentControl.Width - xx - Band;

                }
                if (new_locationY + currentControl.Height + yy > currentControl.Parent.Height)
                {
                    new_locationY = currentControl.Parent.Height - currentControl.Height - yy - Band;


                }




                currentControl.Location = new Point(new_locationX, new_locationY);

                pPoint = cPoint;
                this.currentControl.Refresh();
                //################输出控件移动后的 top 和 left##########################   
                NewTop = new_locationY;
                NewLeft = new_locationX;
                NewWidth = currentControl.Width;
                NewHeight = currentControl.Height;

            }
        }
        /// <summary>
        /// 鼠标弹起事件：让自定义的边框出现
        /// </summary>
        void MouseUp(object sender, MouseEventArgs e)
        {
            this.currentControl.Refresh();
            if (fc != null)
            {
                fc.Visible = true;

                // 调节框控件 重新定位到该控件上不然会在鼠标 移动出容器时 调节框控件 会与本控件位置分离
                fc.Location = new Point(currentControl.Left - Band, currentControl.Top - Band);

                fc.Draw();

            }
        }
        #endregion

        /// <summary>
        /// 重新绘制调节框的新位置
        /// </summary>
        void SetFcNewLocation()
        {
            if (fc != null)
            {
                fc.Visible = true;

                fc.Location = new Point(currentControl.Left - Band, currentControl.Top - Band);

                fc.Draw();
            }

        }


        /// <summary>
        /// 处理键盘方向键移动本控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void myKeydown(object sender, KeyEventArgs key)
        {
            //父容器 大小和工作区域大小的差，去除标题栏和边框的影响
            int useregx = currentControl.Parent.Width - currentControl.Parent.ClientRectangle.Width;
            int useregy = currentControl.Parent.Height - currentControl.Parent.ClientRectangle.Height;
            //可移动的边界极限
            int limitlocationY = currentControl.Parent.Height - currentControl.Height - useregy;
            int limitlocationX = currentControl.Parent.Width - currentControl.Width - useregx;
            switch (key.KeyCode)
            {
                case Keys.Up:
                    if (currentControl.Top >0)
                    {
                    currentControl.Top -= 1;
                    SetFcNewLocation();
                    }
  
                    break;

                case Keys.Down:

                    if (currentControl.Top < limitlocationY)
                    {
                          currentControl.Top += 1;
                    SetFcNewLocation();
                    }
                    else
                    {
                        currentControl.Top = limitlocationY;
                        SetFcNewLocation();
                    }

                    break;
                case Keys.Left:
                    if (currentControl.Left>0)
                    {
                  currentControl.Left -= 1;
                    SetFcNewLocation();
                    }

                    break;

                case Keys.Right:

                    if (currentControl.Left<limitlocationX)
                    {
                     currentControl.Left += 1;
                    SetFcNewLocation();
                    }
                    else
                    {
                        currentControl.Left = limitlocationX;
                        SetFcNewLocation();

                    } 
                    
                    break;
                default:
                    break;
            }


        }


        ////////////////自定义控件显示可调整边框类出现在 父控件的四周 
        ///
        public class FrameControl : UserControl
        {
            #region Constructors
            /// <summary>
            /// 构造函数
            /// </summary>
            public FrameControl(Control ctrl)
            {
                baseControl = ctrl;
                AddEvents();
                CreateBounds();
            }
            #endregion
            #region Fields
            const int Band = 6; //调整大小的响应边框
            private int MinWidth = 10; //最小宽度
            private int MinHeight = 10;//最小高度
            Size square = new Size(Band, Band);//小矩形大小
            Control baseControl; //基础控件，即被包围的控件
            Rectangle[] smallRects = new Rectangle[8];//边框中的八个小圆圈
            Rectangle[] sideRects = new Rectangle[4];//四条边框，用来做响应区域
            Point[] linePoints = new Point[5];//四条边，用于画虚线
            Graphics g; //画图板
            Rectangle ControlRect; //控件包含边框的区域 
            private Point pPoint; //上个鼠标坐标
            private Point cPoint; //当前鼠标坐标
            private MousePosOnCtrl mpoc;
            #endregion
            #region Properties
            /// <summary>
            /// 鼠标在控件中位置
            /// </summary>
            enum MousePosOnCtrl
            {
                NONE = 0,
                TOP = 1,
                RIGHT = 2,
                BOTTOM = 3,
                LEFT = 4,
                TOPLEFT = 5,
                TOPRIGHT = 6,
                BOTTOMLEFT = 7,
                BOTTOMRIGHT = 8,
            }
            #endregion
            #region Methods
            /// <summary>
            /// 加载事件
            /// </summary>
            private void AddEvents()
            {
                this.Name = "FrameControl" + baseControl.Name;
                this.MouseDown += new MouseEventHandler(FrameControl_MouseDown);
                this.MouseMove += new MouseEventHandler(FrameControl_MouseMove);
                this.MouseUp += new MouseEventHandler(FrameControl_MouseUp);
            }
            #region 创建边框
            /// <summary>
            /// 建立控件可视区域
            /// </summary>
            private void CreateBounds()
            {
                //创建边界
                int X = baseControl.Bounds.X - square.Width - 1;
                int Y = baseControl.Bounds.Y - square.Height - 1;
                int Height = baseControl.Bounds.Height + (square.Height * 2) + 2;
                int Width = baseControl.Bounds.Width + (square.Width * 2) + 2;
                this.Bounds = new Rectangle(X, Y, Width, Height);
                this.BringToFront();
                SetRectangles();
                //设置可视区域
                this.Region = new Region(BuildFrame());
                g = this.CreateGraphics();
            }
            /// <summary>
            /// 设置定义8个小矩形的范围
            /// </summary>
            void SetRectangles()
            {
                //左上
                smallRects[0] = new Rectangle(new Point(0, 0), square);
                //右上
                smallRects[1] = new Rectangle(new Point(this.Width - square.Width - 1, 0), square);
                //左下
                smallRects[2] = new Rectangle(new Point(0, this.Height - square.Height - 1), square);
                //右下
                smallRects[3] = new Rectangle(new Point(this.Width - square.Width - 1, this.Height - square.Height - 1), square);
                //上中
                smallRects[4] = new Rectangle(new Point(this.Width / 2 - 1, 0), square);
                //下中
                smallRects[5] = new Rectangle(new Point(this.Width / 2 - 1, this.Height - square.Height - 1), square);
                //左中
                smallRects[6] = new Rectangle(new Point(0, this.Height / 2 - 1), square);
                //右中
                smallRects[7] = new Rectangle(new Point(square.Width + baseControl.Width + 1, this.Height / 2 - 1), square);
                //四条边线
                //左上
                linePoints[0] = new Point(square.Width / 2, square.Height / 2);
                //右上
                linePoints[1] = new Point(this.Width - square.Width / 2 - 1, square.Height / 2);
                //右下
                linePoints[2] = new Point(this.Width - square.Width / 2 - 1, this.Height - square.Height / 2);
                //左下
                linePoints[3] = new Point(square.Width / 2, this.Height - square.Height / 2 - 1);
                //左上
                linePoints[4] = new Point(square.Width / 2, square.Height / 2);
                //整个包括周围边框的范围
                ControlRect = new Rectangle(new Point(0, 0), this.Bounds.Size);
            }
            /// <summary>
            /// 设置边框控件可视区域
            /// </summary>
            /// <returns></returns>
            private GraphicsPath BuildFrame()
            {
                GraphicsPath path = new GraphicsPath();
                //上边框
                sideRects[0] = new Rectangle(0, 0, this.Width - square.Width - 1, square.Height + 1);
                //左边框
                sideRects[1] = new Rectangle(0, square.Height + 1, square.Width + 1, this.Height - square.Height - 1);
                //下边框
                sideRects[2] = new Rectangle(square.Width + 1, this.Height - square.Height - 1, this.Width - square.Width - 1, square.Height + 1);
                //右边框
                sideRects[3] = new Rectangle(this.Width - square.Width - 1, 0, square.Width + 1, this.Height - square.Height - 1);
                path.AddRectangle(sideRects[0]);
                path.AddRectangle(sideRects[1]);
                path.AddRectangle(sideRects[2]);
                path.AddRectangle(sideRects[3]);
                return path;
            }
            #endregion
            /// <summary>
            /// 绘图
            /// </summary>
            public void Draw()
            {
                this.BringToFront();
                //g.FillRectangles(Brushes.LightGray, sideRects); //填充四条边框的内部
                Pen pen = new Pen(Color.Black);
                pen.DashStyle = DashStyle.Dot;//设置为虚线,用虚线画四边，模拟微软效果
                g.DrawLines(pen, linePoints);//绘制四条边线
                g.FillRectangles(Brushes.White, smallRects); //填充8个小矩形的内部
                foreach (Rectangle smallRect in smallRects)
                {
                    g.DrawRectangle(Pens.Black, smallRect);//绘制8个小正方形
                    /* g.DrawEllipse(Pens.Black, smallRect);*/ //绘制8个小椭圆
                }
                //g.DrawRectangles(Pens.Black, smallRects); //绘制8个小矩形的黑色边线
            }
            /// <summary>
            /// 设置光标状态
            /// </summary>
            public bool SetCursorShape(int x, int y)
            {
                Point point = new Point(x, y);
                if (!ControlRect.Contains(point))
                {
                    Cursor.Current = Cursors.Arrow;
                    return false;
                }
                else if (smallRects[0].Contains(point))
                {
                    Cursor.Current = Cursors.SizeNWSE;
                    mpoc = MousePosOnCtrl.TOPLEFT;
                }
                else if (smallRects[1].Contains(point))
                {
                    Cursor.Current = Cursors.SizeNESW;
                    mpoc = MousePosOnCtrl.TOPRIGHT;
                }
                else if (smallRects[2].Contains(point))
                {
                    Cursor.Current = Cursors.SizeNESW;
                    mpoc = MousePosOnCtrl.BOTTOMLEFT;
                }
                else if (smallRects[3].Contains(point))
                {
                    Cursor.Current = Cursors.SizeNWSE;
                    mpoc = MousePosOnCtrl.BOTTOMRIGHT;
                }
                else if (sideRects[0].Contains(point))
                {
                    Cursor.Current = Cursors.SizeNS;
                    mpoc = MousePosOnCtrl.TOP;
                }
                else if (sideRects[1].Contains(point))
                {
                    Cursor.Current = Cursors.SizeWE;
                    mpoc = MousePosOnCtrl.LEFT;
                }
                else if (sideRects[2].Contains(point))
                {
                    Cursor.Current = Cursors.SizeNS;
                    mpoc = MousePosOnCtrl.BOTTOM;
                }
                else if (sideRects[3].Contains(point))
                {
                    Cursor.Current = Cursors.SizeWE;
                    mpoc = MousePosOnCtrl.RIGHT;
                }
                else
                {
                    Cursor.Current = Cursors.Arrow;
                }
                return true;
            }
            /// <summary>
            /// 控件移动
            /// </summary>
            private void ControlMove()
            {
                cPoint = Cursor.Position;
                int x = cPoint.X - pPoint.X;
                int y = cPoint.Y - pPoint.Y;





                switch (this.mpoc)
                {
                    case MousePosOnCtrl.TOP:
                        if (baseControl.Height - y > MinHeight)
                        {
                            baseControl.Top += y;
                            baseControl.Height -= y;
                        }
                        else
                        {
                            baseControl.Top -= MinHeight - baseControl.Height;
                            baseControl.Height = MinHeight;
                        }
                        break;
                    case MousePosOnCtrl.BOTTOM:
                        if (baseControl.Height + y > MinHeight)
                        {
                            baseControl.Height += y;
                        }
                        else
                        {
                            baseControl.Height = MinHeight;
                        }
                        break;
                    case MousePosOnCtrl.LEFT:
                        if (baseControl.Width - x > MinWidth)
                        {
                            baseControl.Left += x;
                            baseControl.Width -= x;
                        }
                        else
                        {
                            baseControl.Left -= MinWidth - baseControl.Width;
                            baseControl.Width = MinWidth;
                        }

                        break;
                    case MousePosOnCtrl.RIGHT:
                        if (baseControl.Width + x > MinWidth)
                        {
                            baseControl.Width += x;
                        }
                        else
                        {
                            baseControl.Width = MinWidth;
                        }
                        break;
                    case MousePosOnCtrl.TOPLEFT:
                        if (baseControl.Height - y > MinHeight)
                        {
                            baseControl.Top += y;
                            baseControl.Height -= y;
                        }
                        else
                        {
                            baseControl.Top -= MinHeight - baseControl.Height;
                            baseControl.Height = MinHeight;
                        }
                        if (baseControl.Width - x > MinWidth)
                        {
                            baseControl.Left += x;
                            baseControl.Width -= x;
                        }
                        else
                        {
                            baseControl.Left -= MinWidth - baseControl.Width;
                            baseControl.Width = MinWidth;
                        }
                        break;
                    case MousePosOnCtrl.TOPRIGHT:
                        if (baseControl.Height - y > MinHeight)
                        {
                            baseControl.Top += y;
                            baseControl.Height -= y;
                        }
                        else
                        {
                            baseControl.Top -= MinHeight - baseControl.Height;
                            baseControl.Height = MinHeight;
                        }
                        if (baseControl.Width + x > MinWidth)
                        {
                            baseControl.Width += x;
                        }
                        else
                        {
                            baseControl.Width = MinWidth;
                        }
                        break;
                    case MousePosOnCtrl.BOTTOMLEFT:
                        if (baseControl.Height + y > MinHeight)
                        {
                            baseControl.Height += y;
                        }
                        else
                        {
                            baseControl.Height = MinHeight;
                        }
                        if (baseControl.Width - x > MinWidth)
                        {
                            baseControl.Left += x;
                            baseControl.Width -= x;
                        }
                        else
                        {
                            baseControl.Left -= MinWidth - baseControl.Width;
                            baseControl.Width = MinWidth;
                        }
                        break;
                    case MousePosOnCtrl.BOTTOMRIGHT:
                        if (baseControl.Height + y > MinHeight)
                        {
                            baseControl.Height += y;
                        }
                        else
                        {
                            baseControl.Height = MinHeight;
                        }
                        if (baseControl.Width + x > MinWidth)
                        {
                            baseControl.Width += x;
                        }
                        else
                        {
                            baseControl.Width = MinWidth;
                        }
                        break;

                }
                pPoint = Cursor.Position;
            }
            #endregion
            #region Events
            /// <summary>
            /// 鼠标按下事件：记录当前鼠标相对窗体的坐标
            /// </summary>
            void FrameControl_MouseDown(object sender, MouseEventArgs e)
            {
                pPoint = Cursor.Position;
            }
            /// <summary>
            /// 鼠标移动事件：让控件跟着鼠标移动
            /// </summary>
            void FrameControl_MouseMove(object sender, MouseEventArgs e)
            {
                if (e.Button == MouseButtons.Left)
                {
                    this.Visible = false;
                    MoveControl.DrawDragBound(baseControl);
                    ControlMove();
                }
                else
                {
                    this.Visible = true;
                    SetCursorShape(e.X, e.Y); //更新鼠标指针样式
                }
            }
            /// <summary>
            /// 鼠标弹起事件：让自定义的边框出现
            /// </summary>
            void FrameControl_MouseUp(object sender, MouseEventArgs e)
            {
                this.baseControl.Refresh(); //刷掉黑色边框
                this.Visible = true;
                CreateBounds();
                Draw();

            }
            #endregion





        }
    }
}
